// 导入React
import React from 'react';
// 导入Radix UI Popover原语
import * as RadixPopover from '@radix-ui/react-popover';
// 导入工具函数
import { cn } from '@/lib/utils';
// 导入按钮组件
import { Button } from './Button';

// 确认气泡对话框属性接口
interface ConfirmPopoverProps {
    // 是否打开
    open: boolean;
    // 关闭回调
    onClose: () => void;
    // 确认回调
    onConfirm: () => void;
    // 触发元素引用
    triggerRef: React.RefObject<HTMLElement>;
    // 确认按钮文本
    confirmText?: string;
    // 取消按钮文本
    cancelText?: string;
    // 确认按钮变体
    confirmVariant?: 'primary' | 'danger';
    // 加载状态
    loading?: boolean;
    // CSS类名
    className?: string;
}

// 确认气泡对话框组件
// 现代化设计：基于Radix UI的稳定实现
export const ConfirmPopover: React.FC<ConfirmPopoverProps> = ({
    open,
    onClose,
    onConfirm,
    triggerRef,
    confirmText = '确定',
    cancelText = '取消',
    confirmVariant = 'danger',
    loading = false,
    className
}) => {
    // 处理确认操作
    const handleConfirm = () => {
        onConfirm();
    };

    return (
        <RadixPopover.Root open={open} onOpenChange={(isOpen) => !isOpen && onClose()} modal={false}>
            {/* 使用现有按钮作为触发器 */}
            <RadixPopover.Anchor asChild>
                {(() => {
                    const rect = triggerRef.current?.getBoundingClientRect();
                    return (
                        <div
                            // 说明：用 fixed 基于视口定位，避免容器位移/滚动造成锚点偏移
                            style={{
                                position: 'fixed',
                                left: rect?.left ?? 0,
                                top: rect?.top ?? 0,
                                width: rect?.width ?? 0,
                                height: rect?.height ?? 0,
                                pointerEvents: 'none'
                            }}
                        />
                    );
                })()}
            </RadixPopover.Anchor>

            {/* 气泡框内容 */}
            <RadixPopover.Portal>
                <RadixPopover.Content
                    className={cn(
                        'z-50 rounded-xl border border-gray-200/60 bg-white p-2.5 shadow-xl min-w-[120px]',
                        'backdrop-blur-sm animate-in fade-in-0 zoom-in-95',
                        'data-[side=bottom]:slide-in-from-top-2',
                        'data-[side=left]:slide-in-from-right-2',
                        'data-[side=right]:slide-in-from-left-2',
                        'data-[side=top]:slide-in-from-bottom-2',
                        className
                    )}
                    side="bottom"
                    align="center"
                    sideOffset={8}
                    collisionPadding={8}
                    // 关闭 Radix 的自动聚焦（防止按钮在打开/窗口切回时被强制聚焦）
                    onOpenAutoFocus={(e) => e.preventDefault()}
                    onCloseAutoFocus={(e) => e.preventDefault()}
                >
                    {/* 操作按钮组 */}
                    <div className="flex gap-1.5">
                        {/* 取消按钮 */}
                        <Button
                            variant="ghost"
                            size="sm"
                            onClick={onClose}
                            disabled={loading}
                            className={cn(
                                'h-8 px-3 text-sm font-normal',
                                'text-gray-700 hover:text-gray-900',
                                'bg-gray-100 hover:bg-gray-200 active:bg-gray-300',
                                'rounded-lg border-0 shadow-none',
                                'transition-all duration-200 ease-out',
                                'transform hover:scale-[1.02] active:scale-[0.98]'
                            )}
                        >
                            {cancelText}
                        </Button>

                        {/* 确认按钮 */}
                        <Button
                            variant={confirmVariant}
                            size="sm"
                            onClick={handleConfirm}
                            loading={loading}
                            className={cn(
                                'h-8 px-3 text-sm font-medium',
                                'rounded-lg border-0',
                                'shadow-sm hover:shadow-md active:shadow-sm',
                                'transition-all duration-200 ease-out',
                                'transform hover:scale-[1.02] active:scale-[0.98]',
                                confirmVariant === 'danger' && [
                                    'bg-red-500 hover:bg-red-600 active:bg-red-700',
                                    'text-white shadow-red-500/25 hover:shadow-red-500/30'
                                ]
                            )}
                        >
                            {confirmText}
                        </Button>
                    </div>

                    {/* Radix自动生成的箭头，带边框 */}
                    <RadixPopover.Arrow
                        className="fill-white stroke-gray-200/60 stroke-1"
                        width={16}
                        height={8}
                    />
                </RadixPopover.Content>
            </RadixPopover.Portal>
        </RadixPopover.Root>
    );
};
